<?php

namespace App\Models;

use App\Services\AlipayService;
use App\Services\OrderService;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class OtherWithholdLog extends Model
{
    use HasFactory;
    protected $table = 'sp_other_withhold_log';
    protected $primaryKey = 'id';
    public $timestamps = false;

    const PAY_TYPE_ZM = 1;//扣款
    const PAY_TYPE_PREPAYMENT = 2;//主动支付
    const PAY_TYPE_HUABEI = 3;//花呗支付
    const PAY_TYPE_MANUAL_ZM = 4;//手动代扣
    const PAY_TYPE_DEPOSIT = 5;//押金扣除
    const PAY_TYPE_ANTCHAIN = 6;//智能合同代扣
    const PAY_TYPE_YIFUBAO=7; //易付宝
    const PAY_TYPE_WXPAY=8; //微信支付

    const PAY_TYPE_LIST = [
        "1"=>"预授权扣款",
        "2"=>"主动支付",
        "3"=>"花呗支付",
        "4"=>"手动代扣",
        "5"=>"智能合同代扣",
        "6"=>"接口请求代扣",
        "7"=>'易付宝支付',
        "8"=>'微信支付',
    ];

    const STATUS_FAIL = 0;//失败
    const STATUS_SUCCESS = 1;//成功
    const STATUS_LIST = [
        "0"=>"失败",
        "1"=>"成功",
    ];

    /**
     * 履约记录
     * @param $order_no
     * @param $lease_id
     * @param $out_trade_no
     * @param $trade_no
     * @param $result
     * @param bool $status
     */
    public static function orderWithholdLog($order_no, $lease_id, $out_trade_no, $trade_no, $result, $type = self::PAY_TYPE_ZM, $status = true, $admin_id, $partial_amount = 0, $coupon = 0)
    {
        $data = [
            'order_no' => $order_no,
            'lease_id' => $lease_id,
            'out_trade_no' => $out_trade_no ? $out_trade_no : 0,
            'trade_no' => $trade_no ? $trade_no : 0,
            'status' => $status ? 1 : 0,
            'result' => json_encode($result),
            'pay_type' => $type,
            'admin_id' => $admin_id,
            'partial_amount' => $partial_amount,
            'merchant_contribute' => $coupon,
        ];
        if (OtherWithholdLog::where([['order_no', $order_no], ['lease_id', $lease_id], ['out_trade_no', $out_trade_no], ['status', 1]])->count() == 0) {
            OtherWithholdLog::insert($data);
        }
        //查找扣款失败未履约的订单
//        if ($status) {
//
////            $orderModel = Order::findByTradeNo($order_no);
////            $log = OtherWithholdLog::where(['order_no' => $order_no, 'lease_id' => $lease_id, 'status' => self::STATUS_FAIL])
////                ->whereIn('pay_type', [self::PAY_TYPE_ZM, self::PAY_TYPE_MANUAL_ZM])
////                ->groupBy('out_trade_no')
////                ->get();
////            foreach ($log as $value) {
////                $orderData = [
////                    'orderId' => $value['order_no'],
////                    'outTradeNo' => $value['out_trade_no'],
////                    'tradeNo' => $value['trade_no'],
////                    'status' => 'CLOSED',
////                ];
////                AlipayService::orderInfo($orderModel->mini_id, $orderData);
////            }
//        } else {
//            //发送扣款失败短信
//            self::sendSms($lease_id);
//        }
    }

    /**
     * 发送扣款失败短信
     * @param $lease_id
     */
    public static function sendSms($lease_id){

        $where[] = ['template_id',SmsTemplate::SMS_TEMPLATE_WITHHOLD_FAIL];
        $where[] = ['lease_id',$lease_id];
        $count = SmsRecord::where($where)->count('id');

        if($count <= 3){
            $lease = obToArray(Order::from('sp_order_2 as o')
                ->select('o.seller_id','o.trade_no','ol.id','m.mobile','ol.which_period','ol.rent')
                ->leftjoin('sp_order_lease_2 as ol', 'o.id','ol.order_id')
                ->leftjoin('sp_member_2 as m','o.uid','m.id')
                ->where(['ol.id'=>$lease_id])
                ->first());
            //发送短信
            $res = ShopSms::withholdFail($lease['seller_id'],$lease['mobile'],$lease['which_period'],$lease['rent'],$lease['trade_no'],$lease['id']);
        }
    }

    /**
     * 获取账单支付流水
     * @param string $orderNO
     * @param string $LeaseId
     * @return array
     */
    public static function getFlow($orderNO='',$LeaseId=''){
        $where = [];
        if($orderNO){
            $where['log.order_no'] = $orderNO;
        }
        if($LeaseId){
            $where['log.lease_id'] = $LeaseId;
        }

        $log = OtherWithholdLog::from('sp_other_withhold_log as log')
            ->where($where)
            ->leftjoin('sp_other_admin as a','a.id','log.admin_id')
            ->leftjoin('sp_order_2 as o','o.trade_no','log.order_no')
            ->select(
                'log.status','log.trade_no as out_trade_no','log.create_time','log.pay_type as log_pay_type','log.lease_id'
                ,'a.username' ,'log.partial_amount'
                ,'o.id','log.pay_type','o.rent_total','o.month_total'
            )
            ->orderBy('log.id', 'desc')->get();
        $log = obToArray($log);
        if($log){
            foreach ($log as &$item){
                if($LeaseId){
                    $leaseValue = OrderLease::where(['id'=>$LeaseId])->value('status');
                    $item['lease_status'] = OrderLease::ORDER_LEASE_STATUS_LIST[$leaseValue];
                    $pay_type_name = OtherWithholdLog::PAY_TYPE_LIST[$item['log_pay_type']];
                    if($item['status'] == OtherWithholdLog::STATUS_SUCCESS){
                        $item['pay_type_status'] = $pay_type_name.'成功';
                        $item['failReason'] = '';
                    }else{
                        $item['pay_type_status'] = $pay_type_name.'失败';
                        $item['failReason'] = '余额不足';
                    }
                }
                if($item['pay_type'] == Order::ORDER_PAY_TYPE_HUABEI){
                    $item['rent'] = $item['rent_total'];
                    $item['which_period'] = $item['month_total'];
                }else{
                    $lease = OrderLease::where(['id'=>$item['lease_id']])->select('rent','which_period')->first();
                    $lease = obToArray($lease);
                    if($lease){
                        $item['rent'] = $item['partial_amount']? $item['partial_amount']:$lease['rent'];
                        $item['which_period'] = $lease['which_period'];
                    }
                }
            }
        }
        return  obToArray($log);
    }
}
